package softtech.apps.customadapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import softtech.apps.autoanswerphonecall.R;
import softtech.apps.model.DatabaseHandler;
import softtech.apps.model.RowRecord;
import softtech.apps.sync.android.util.RowRecordComparator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ItemRecordAdapter extends BaseAdapter {

	private Context mContext;

	private List<RowRecord> list;
	AudioManager am;
	public static final String FILE_DIRECTORY = "softtech";

	private RadioButton mSelectedRB;

	private RowRecordComparator mComparator = RowRecordComparator
			.getNameAsc(true);

	private DatabaseHandler dbHandler;

	private int mSelectedPosition = 0;

	public static final String RECORD_DEFAULT = "Record Default";

	public ItemRecordAdapter(Context context, List<RowRecord> lst) {
		mContext = context;
		list = new ArrayList<RowRecord>();
		list = lst;

		RowRecord rr = new RowRecord(RECORD_DEFAULT, "leave_message_please");

		dbHandler = new DatabaseHandler(mContext);

		Collections.sort(list, mComparator);

		list.add(0, rr);

		setRecordDefault();

	}

	private void setRecordDefault() {

		if (list != null) {
			int size = list.size();

			mSelectedPosition = 0;

			RowRecord rr = dbHandler.getNameRecordDefault();

			String nameDefault = rr.getmFileName() + "-.mp3";
//			Log.e("NAME DEFAULT SELECT", nameDefault);
//			Log.e("NAME DEFAULT SELECT", rr.getmFilePath());
//			Log.e("NAME DEFAULT SELECT", "--------------------------");
			for (int i = 1; i < size; i++) {

//				Log.e("ANME", list.get(i).getmFileName());
//				Log.e("PATH", list.get(i).getmFilePath());
				String name = list.get(i).getmFileName();

				if (name.trim().compareTo(nameDefault.trim()) == 0) {
					mSelectedPosition = i;
				}

			}
		}
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	public Boolean removeItem(int position) {
		String file_path = list.get(position).getmFilePath();
		//Log.d("REMOVE", "File path = " + file_path);
		File file = new File(file_path);
		boolean deleted = file.delete();
		if (deleted) {
			list.remove(position);
			notifyDataSetChanged();
		}
		return deleted;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		ViewHolder viewHolder = null;

		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			convertView = inflater
					.inflate(R.layout.item_answer_by_record, null);

			viewHolder = new ViewHolder();

			viewHolder.bt_play = (Button) convertView
					.findViewById(R.id.bt_play);
			viewHolder.relativeLayout = (RelativeLayout) convertView
					.findViewById(R.id.layoutRela);
			viewHolder.rad_check_default = (RadioButton) convertView
					.findViewById(R.id.rad_check_default);
			viewHolder.tv_date_time = (TextView) convertView
					.findViewById(R.id.tv_date_time);
			viewHolder.tv_title = (TextView) convertView
					.findViewById(R.id.tv_item_record_title);

			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		if (position == 0) {

			viewHolder.tv_title.setText(RECORD_DEFAULT);
			viewHolder.tv_date_time.setVisibility(View.GONE);
		} else {

			String name[] = list.get(position).getmFileName().split("-");
			viewHolder.tv_title.setText(name[0]);
			viewHolder.tv_date_time.setVisibility(View.VISIBLE);
			viewHolder.tv_date_time.setText(getDate(Long.parseLong(name[1]),
					"MM-dd-yyy hh:mm:ss"));

		}

		mSelectedRB = viewHolder.rad_check_default;

		viewHolder.rad_check_default.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mSelectedPosition != position && mSelectedRB != null) {
					mSelectedRB.setChecked(false);

					mSelectedPosition = position;

					String name = list.get(position).getmFileName();

					if (name.trim().compareTo(RECORD_DEFAULT) == 0) {
						name = DatabaseHandler.RECORD_RAW_DEFAULT;

						dbHandler.updateNameRecordDefault(name, "null");
					} else {
						name = name.substring(0, name.indexOf(".") - 1);
						dbHandler.updateNameRecordDefault(name,
								list.get(position).getmFilePath());
					}

					mSelectedRB = (RadioButton) v;

					notifyDataSetChanged();
				}
			}
		});

		if (mSelectedPosition != position) {

			mSelectedRB.setChecked(false);
		} else {

			mSelectedRB.setChecked(true);

			if (mSelectedRB != null
					&& viewHolder.rad_check_default != mSelectedRB) {
				mSelectedRB = viewHolder.rad_check_default;
			}
		}

		return convertView;
	}

	@SuppressLint("SimpleDateFormat")
	public String getDate(long milliSeconds, String dateFormat) {
		// Create a DateFormatter object for displaying date in specified
		// format.
		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);

		// Create a calendar object that will convert the date and time value in
		// milliseconds to date.
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliSeconds);
		return formatter.format(calendar.getTime());
	}

	static class ViewHolder {

		RelativeLayout relativeLayout;
		RadioButton rad_check_default;
		Button bt_play;
		TextView tv_title;
		TextView tv_date_time;

	}
	// private void PlayingSound(String path) {
	//
	// am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
	// if (!am.isSpeakerphoneOn()) {
	// am.setSpeakerphoneOn(true);
	// }
	// am.setMode(AudioManager.STREAM_MUSIC);
	// int volume_level = am.getStreamVolume(AudioManager.STREAM_MUSIC);
	// int max_volume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	// if (volume_level < max_volume) {
	// am.setStreamVolume(AudioManager.STREAM_MUSIC, max_volume,
	// AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
	// }
	// player = new MediaPlayer();
	// player.setAudioStreamType(AudioManager.STREAM_MUSIC);
	// // player.setVolume(AudioManager.MODE_NORMAL, AudioManager.MODE_NORMAL);
	// try {
	// player.setDataSource(path);
	// } catch (IllegalArgumentException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// } catch (SecurityException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// } catch (IllegalStateException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// } catch (IOException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// }
	// player.setOnCompletionListener(new OnCompletionListener() {
	// @Override
	// public void onCompletion(MediaPlayer mp) {
	// // TODO Auto-generated method stub
	// mp.stop();
	// mp.reset();
	// mp.release();
	// mp = null;
	// am.setSpeakerphoneOn(false);
	// Log.d("MUSIC", "Music player has finish");
	// }
	//
	// });
	// player.setOnPreparedListener(new OnPreparedListener() {
	// @Override
	// public void onPrepared(MediaPlayer mp) {
	// // Do something. For example: playButton.setEnabled(true);
	// }
	// });
	//
	// try {
	// player.prepare();
	// } catch (IllegalStateException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// player.start();
	//
	// }

	// private void StopPlay() {
	// if (player != null) {
	// player.stop();
	// player.reset();
	// player.release();
	// player = null;
	// }
	// }

}
